﻿using System;
using System.Collections.Generic;
using System.Net;


namespace ET
{
	[MessageHandler]
	public class C2R_RegisterHandler : AMRpcHandler<C2R_Register, R2C_Register>
	{
		protected override async ETTask Run(Session session, C2R_Register request, R2C_Register response, Action reply)
		{
			try
            {
				DBComponent db = session.Domain.GetComponent<DBComponent>();
				List<TAccount> result = await db.Query<TAccount>(x => x.Account == request.Account);
				if(result.Count >= 1)
                {
					response.Error = ErrorCode.ERR_Error;
					response.Message = "账号已存在";
					reply();
					return;
				}

				//生成账号信息
				TAccount newAccount = EntityFactory.CreateWithId<TAccount>(session.Domain,IdGenerater.Instance.GenerateId());
				newAccount.Account = request.Account;
				newAccount.Password = request.Password;
				await db.Save(newAccount);

				//生成玩家信息
				TUser newUser = EntityFactory.CreateWithId<TUser, string>(session.Domain, newAccount.Id, newAccount.Account);
				await db.Save(newUser);

				response.Error = ErrorCode.ERR_Success;
				reply();
			}
			catch(Exception e)
            {
				ReplyError(response, e, reply);
            }


			
		}
	}
}